﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TicTacToeControl
{
    public class State
    {
        private bool _playerOneTurn;
        private bool _haveWinner;
        private bool _isLegal;
        private int _movesTaken;
        private Player _playerOne;
        private Player _playerTwo;
        private Board _board;

        public State(String playerOneName, String playerTwoName)
        {
            _haveWinner = false;
            _movesTaken = 0;
            _playerOneTurn = GetRandomPlayerTurn();
            _playerOne = new Player(playerOneName, 1);
            _playerTwo = new Player(playerTwoName, 2);
            _board = new Board();
        }

        public bool HaveWinner
        {
            get { return _haveWinner; }
        }

        public bool MoreMovesAval
        {
            get
            {
                if (_movesTaken == 9)
                    return false;
                else
                    return true;
            }
        }

        public bool IsPlayerOneTurn
        {
            get { return _playerOneTurn; }
        }

        public bool PlacePiece(int x, int y)
        {
            if (_playerOneTurn)
            {
                _isLegal = _board.PlacePiece(x, y, _playerOne);
                _haveWinner = _board.CheckForWin(_playerOne);
            }

            else
            {
                _isLegal = _board.PlacePiece(x, y, _playerTwo);
                _haveWinner = _board.CheckForWin(_playerTwo);
            }

            if (_isLegal)
            {
                _movesTaken++;
                _playerOneTurn = !_playerOneTurn;
            }
            return _isLegal;
        }

        public void RestartGame()
        {
            _board.ClearBoard();
        }

        private bool GetRandomPlayerTurn()
        {
            Random rand = new Random();
            if (rand.Next(0, 2) == 1)
                return true;
            else
                return false;
        }
    }
}
